package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import dto.UserDTO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "user:verify:code:";

    @Override
    public Boolean exists(String date, Integer type) {
        if (StringUtils.isBlank(date) || (1 != type && 2 != type)) {
            throw new LyException(400, "请求参数错误");
        }

        String num = null;
        switch (type) {
            case 1:
                num = "username";
                break;
            case 2:
                num = "password";
        }

        return query().eq(num, date).count() == 1;
    }

    @Override
    public void sendCode(String phone) {
        //1, 验证手机号码的格式
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }
        //2 , 使用Apache的工具类生成六位数的数字验证码
        String code = RandomStringUtils.randomNumeric(6);

        //3, 保存验证码到redis中
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 24, TimeUnit.HOURS);

        //4, 发送到RabbitMQ消息到ly-sms
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);

        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

    }
     //加密工具
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void register(User user, String code) {
        //唯一phone
        String key = KEY_PREFIX + user.getPhone();

        if (!redisTemplate.hasKey(key) || !redisTemplate.opsForValue().get(key).equals(code)) {
            throw new LyException(400, "验证码输入有误或过期");
        }

        String encode = passwordEncoder.encode(user.getPassword());

        user.setPassword(encode);
        save(user);

    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {
        User user = query().eq("username", username).one();
        //从加密的password中推测出盐值,然后盐值对明文的密码加密之后自动匹配
        if(user==null||!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或者密码错误");
        }
        UserDTO userDTO = BeanHelper.copyProperties(user, UserDTO.class);
        return userDTO;
    }


}